<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	
	<body>
		<script>
			/* 219971311胡少康 */
			class Commitment {
				static PENDING = '待定' ; static FULFILLED= '成功' ; static REJECTED= '拒绝' ;
				constructor( func){
					//设置初始状态为待定
					this.status = Commitment.PENDING;
					this.result = null;
					//用数组保存resolve函数
					this.resolvecallbacks =[];
					//用数组保存reject函数
					this.rejectcallbacks =[];
					try {
						func(this.resolve.bind(this),this.reject.bind(this));
					} 
					catch (error){
						this.reject(error);
					}
				}
			
				resolve(result){
					//添加setTimeout函数使得函数最后执行
					setTimeout(() => {
						if(this.status === Commitment. PENDING){
							this.status = Commitment. FULFILLED;
							this.result = result;
							//查看是否有传入的待执行函数，如果用就逐个执行
							this.resolvecallbacks.forEach(callback => {
								callback(result);
							});
						}
					});
				}
				reject (result) {
					//添加setTimeout函数使得函数最后执行
					setTimeout(() => {
						if(this.status === Commitment.PENDING)
						{
							this.status = Commitment.REJECTED;
							this.result = result;
							//查看是否有传入的待执行函数，如果用就逐个执行
							this.rejectcallbacks.forEach(callback => {
								callback(result);
							});
						}
					});
				}
				
				then(onFULFILLED , onREJECTED){
					//返回一个新的Promise实现链式调用
					return new Commitment((resolve,reject) => {
						//如果传入的参数不是函数就转化为一个空函数
						onFULFILLED = typeof onFULFILLED === 'function'? onFULFILLED : () => {};
						onREJECTED = typeof onREJECTED === 'function' ? onREJECTED : () => {};
						if(this.status === Commitment.PENDING){
							//如果函数依旧是待定状态，就将函数存放到数组中
							this.resolvecallbacks.push(onFULFILLED);
							this.rejectCallbacks.push(onREJECTED);
						}
						if(this.status === Commitment.FULFILLED){
							//判断条件符合后执行异步操作
							setTimeout(() => {
								onFULFILLED( this.result);
							});
						}
						if( this.status === Commitment.REJECTED){
							//判断条件符合后执行异步操作
							setTimeout(() => {
								onREJECTED( this.result);
							});
						}
					});
				}
			}
			console.log("第一步");
			let commitment =new Commitment((resolve, reject) => {
				console.log("第二步");
				resolve( '这次一定' );
			});
			commitment.then(
				result => {console.log(result)},
				result => {console.log(result.message)}
			);
			console.log("第三步");
		</script>
	</body>
</html>